package cn.ycc1.boot3tx.service.impl;

import cn.ycc1.boot3tx.domain.Account;
import cn.ycc1.boot3tx.domain.dto.BuyBookDTO;
import cn.ycc1.boot3tx.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ycc1.boot3tx.domain.Book;
import cn.ycc1.boot3tx.service.BookService;
import cn.ycc1.boot3tx.mapper.BookMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
* @author mi
* @description 针对表【book】的数据库操作Service实现
* @createDate 2024-12-17 21:07:18
*/
@Service
@RequiredArgsConstructor
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>
    implements BookService{
    private final AccountService accountService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void decreaseStock(Integer bookId, Integer quantity) {
        Book book = getById(bookId);
        int i = 10 / 0;
        if(book != null){
            book.setStock(book.getStock() - quantity);
            updateById(book);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void decreaseBalance(Integer userId, BigDecimal amount) {
        Account account = accountService.getById(userId);
        if(account.getBalance().compareTo(amount) < 0){
            throw new RuntimeException("余额不足");
        }
        account.setBalance(account.getBalance().subtract(amount));
        accountService.updateById(account);
    }
}




